package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.common.client.ItemClient;
import com.hmall.order.constant.MqConstant;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Ronin
 * @date 2023/4/10 17:38
 * @Version 1.0
 * @Description:订单监听器
 */
@Component
public class OrderListener {
    /**
     * 注入IOrderService
     */
    @Resource
    private IOrderService orderService;
    /**
     * 注入OrderDetailMapper
     */
    @Resource
    private OrderDetailMapper orderDetailMapper;
    /**
     * 注入ItemClient
     */
    @Resource
    private ItemClient itemClient;

    /**
     * 监听到超时订单后操作
     *
     * @param orderId
     */
    @RabbitListener(queues = MqConstant.ORDER_DL_QUEUE)
    public void handleCancelOrder(Long orderId) {
        System.out.println("订单超时，获取超时订单id" + orderId);
        //根据id查询订单
        Order order = orderService.getById(orderId);
        //判断status是否为1
        if (order.getStatus() != 1) {
            //不为1丢弃
            return;
        }
        //为1继续
        //根据orderId查询订单详情，得到商品购买数量
        OrderDetail orderDetail = orderDetailMapper.getByOrderId(orderId);
        orderDetail.getNum();
        //修改订单status状态为5
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", 5);
        orderService.update(updateWrapper);
        //调用item-service，根据id，数量，恢复库存
        itemClient.updateStock(orderDetail.getItemId(), -orderDetail.getNum());
        //库存恢复成功
        System.out.println("库存恢复成功");
    }
}
